const express = require('express');
const router = express.Router();
const ddModel = require('../models/dd');
const User = require('../models/User');
const errorRes = (res, message, code = 400) => res.status(code).json({ code, message });

// 创建订单
router.post('/ddcreate', async (req, res) => {
  try {
    const order = await ddModel.create(req.body);
    res.json({ code: 200, msg: '创建订单成功' });
    const io = req.app.get('io');
    if (io) {
      io.emit('newOrder', order); // 向所有socket客户端推送新订单
    }
    if (io && req.body.userId) {
      io.to(req.body.userId).emit('orderCreated', {
        orderId: order._id,
        message: '您的订单已创建成功！',
        order
      });
    }
  } catch (e) {
    errorRes(res, '创建订单失败', 500);
  }
});

// 获取订单列表
router.get('/list', async (req, res) => {
  try {
    const { userId } = req.query;
    const query = {};
    if (userId) query.userId = userId;
    if (userId) {
      const User = require('../models/User');
      const user = await User.findById(userId);
      if (!user || user.status !== '正常') {
        return errorRes(res, '当前账号状态异常，无法进行订单管理操作，请联系管理员。', 403);
      }
    }
    const orders = await ddModel.find(query);
    res.json({ code: 200, data: orders });
  } catch (e) {
    errorRes(res, e.message, 500);
  }
});

// 按省份分组的订单数据
router.get('/by-province', async (req, res) => {
  try {
    const provinceData = await ddModel.aggregate([
      { $match: { provinceName: { $exists: true, $ne: null } } },
      {
        $group: {
          _id: "$provinceName",
          orderCount: { $sum: 1 },
          productCount: { $sum: { $toInt: "$num" } },
          salesAmount: { $sum: { $multiply: [{ $toDouble: "$price" }, { $toInt: "$num" }] } }
        }
      },
      {
        $project: {
          provinceName: "$_id",
          orderCount: 1,
          productCount: 1,
          salesAmount: { $round: ["$salesAmount", 2] },
          _id: 0
        }
      },
      { $sort: { salesAmount: -1 } }
    ]);
    res.json({ code: 200, data: provinceData });
  } catch (e) {
    errorRes(res, e.message || '服务器内部错误', 500);
  }
});

// 按年份和月份分组的订单数据
router.get('/by-year-month', async (req, res) => {
  try {
    const yearMonthData = await ddModel.aggregate([
      { $match: { date: { $exists: true, $ne: null } } },
      { $addFields: { year: { $year: "$date" }, month: { $month: "$date" } } },
      {
        $group: {
          _id: { year: "$year", month: "$month" },
          orderCount: { $sum: 1 },
          productCount: { $sum: { $toInt: "$num" } },
          salesAmount: { $sum: { $multiply: [{ $toDouble: "$price" }, { $toInt: "$num" }] } }
        }
      },
      {
        $project: {
          year: "$_id.year",
          month: "$_id.month",
          orderCount: 1,
          productCount: 1,
          salesAmount: { $round: ["$salesAmount", 2] },
          _id: 0
        }
      },
      { $sort: { year: 1, month: 1 } }
    ]);
    const groupedByYear = {};
    yearMonthData.forEach(item => {
      const { year, month, orderCount, productCount, salesAmount } = item;
      if (!groupedByYear[year]) {
        groupedByYear[year] = {
          year,
          months: Array(12).fill().map(() => ({ orderCount: 0, productCount: 0, salesAmount: 0 })),
          totalOrders: 0,
          totalProducts: 0,
          totalSales: 0
        };
      }
      const monthIndex = month - 1;
      groupedByYear[year].months[monthIndex] = { orderCount, productCount, salesAmount };
      groupedByYear[year].totalOrders += orderCount;
      groupedByYear[year].totalProducts += productCount;
      groupedByYear[year].totalSales += salesAmount;
    });
    const result = Object.values(groupedByYear).sort((a, b) => a.year - b.year);
    res.json({ code: 200, data: result, message: "获取年度月度订单数据成功" });
  } catch (e) {
    errorRes(res, e.message || '服务器内部错误', 500);
  }
});

// 更新订单状态
router.post('/update/:id', async (req, res) => {
  try {
    const { id } = req.params;
    const { status } = req.body;
    const updated = await ddModel.findByIdAndUpdate(id, { status }, { new: true });
    if (!updated) return errorRes(res, '订单不存在', 404);
    res.json({ code: 200, message: '订单状态更新成功', data: updated });
  } catch (e) {
    errorRes(res, '订单状态更新失败', 500);
  }
});



// 获取订单列表
router.get('/quan', async (req, res) => {
  try {
    const { logid } = req.query
    const query = {}
    if (logid) query.logid = logid


    const orders = await ddModel.find(query)
    res.json({
      code: 200,
      orders
    });
  } catch (error) {
    res.status(500).json({
      code: 500,
      message: error.message
    });
  }
});

//获取对应的商户名称
router.get('/shang', async (req, res) => {
  const list = await User.find()
  res.send({
    code: 200,
    list
  })
});

// 修改订单状态
router.post('/update-status', async (req, res) => {
  try {
    const { _id, status } = req.body;

    // 更新订单状态
    const updatedOrder = await ddModel.findByIdAndUpdate(
      _id,
      { status }
    );

    if (!updatedOrder) {
      return res.status(404).json({
        code: 404,
        message: '未找到对应的订单'
      });
    }

    res.json({
      code: 200,
      message: '订单状态更新成功',
      data: updatedOrder
    });
  } catch (error) {
    console.error("更新订单状态失败:", error);
    res.status(500).json({
      code: 500,
      message: error.message || "服务器内部错误"
    });
  }
});

// 确认收货
router.post('/confirm-receive', async (req, res) => {
  try {
    const { _id } = req.body;
    const updated = await ddModel.findByIdAndUpdate(_id, { status: '已收货' }, { new: true });
    if (!updated) return errorRes(res, '订单不存在', 404);
    // Socket.io 推送
    const io = req.app.get('io');
    if (io) {
      io.emit('orderStatusChanged', { _id, status: '已收货' });
    }
    res.json({ code: 200, message: '确认收货成功', data: updated });
  } catch (e) {
    errorRes(res, '确认收货失败', 500);
  }
});

// 删除订单
router.delete('/delete', async (req, res) => {
  try {
    // 从请求体获取订单ID
    const { _id } = req.body;

    // 参数校验：检查订单ID是否存在
    if (!_id) {
      return res.status(400).json({
        code: 400,
        message: '缺少必要参数：订单ID（_id）'
      });
    }

    // 执行删除操作
    const deletedOrder = await ddModel.findByIdAndDelete(_id);

    // 检查订单是否存在
    if (!deletedOrder) {
      return res.status(404).json({
        code: 404,
        message: '未找到对应的订单，删除失败'
      });
    }

    // 删除成功返回结果
    res.json({
      code: 200,
      message: '订单删除成功',
      data: deletedOrder // 返回被删除的订单信息（可选）
    });
  } catch (error) {
    console.error("删除订单失败:", error);
    res.status(500).json({
      code: 500,
      message: error.message || "服务器内部错误，删除订单失败"
    });
  }
});



module.exports = router; 